<?php
namespace app\front\service\v1;
use think\Session;
use app\front\service\v1\Notify as NotifyService;
use app\front\model\Store as StoreModel;
use app\front\model\Shop as ShopModel;
use app\front\model\Account as AccountModel;
use app\front\model\Filiale as FilialeModel;
use app\front\model\Discount as DiscountModel;
use app\front\model\Award as AwardModel;
use app\front\model\Awardrecord as AwardrecordModel;
     class RedPack extends NotifyService
{
    public  function HongBao($mch_billno){
        $TemporaryMsg=$this->getTemporaryForMchId($mch_billno);
        //获取客户号
        $store_name=$TemporaryMsg['store_name'];
        $customer_id=$TemporaryMsg['open_id'];
        $store_id =$TemporaryMsg['store_id'];
        $moneyNum = $TemporaryMsg['total_fee'];
        $moneyNum= bcdiv($moneyNum,100,3);
        $moneyNum=10;
        //获取红包金额
        $red_packet=$this->award_prob( $store_id, $customer_id,  $moneyNum,$mch_billno);
        //获取红包金额
        $params=$this->getHbXmlParams($mch_billno, $red_packet,$store_name, $customer_id);
        //向微信服务器红包地址发送参数
        $retuen_params= postStr(config('HONGBAOURL'),$params);
        logs("HongBaoHistory.txt", $retuen_params);
        $retuen_params2=XmlToArr($retuen_params);
        if($retuen_params2['return_code'] == 'SUCCESS' && $retuen_params2['result_code'] == 'SUCCESS'){
            //插入中奖纪录
            $award_money=  bcdiv($retuen_params2['total_amount'],100,2);
            $retuen_params2 = ['record_statu'=>1,'msg'=>$retuen_params2['return_msg'],'award_money'=>$award_money];
            AwardrecordModel::where('mch_billno',$mch_billno)->update($retuen_params2);
        }
         $this->NotityForBoss($mch_billno);
        $userinfoMsg=$this->getUserinfoForOpenid( $customer_id);
        $shareNum=$userinfoMsg['shareNum'] ; 
        $subscribe= $userinfoMsg['subscribe'] ; 
        if($shareNum<2){
            //  $this->logs("test.txt", $this->TodayisExistShareHongBao($openid).$openidNum);
            if($this->TodayisExistShareHongBao($customer_id)){
                $this->NotityForMemberNoShare($mch_billno, $store_id);
            }else{
                $this->NotityForMember($mch_billno,$store_id);
            }
        }else{
            
            $this->NotityForMemberNoShare($mch_billno, $store_id);
        }    
        //将微信服务器返回参数记录到日志
        Session::set('moneyNum',$moneyNum);
        Session::set('red_packet',$red_packet);
        logs('log_return_hongbao.txt', $retuen_params);
      //   $this->display('success');
    }
    
    /*
    * 函数用途描述:获取红包返红包所用的xml数据
    
    * @param: $mch_billn 商户订单号,$red_packet（红包金额 分度值：分）
    
    * @return:返回XML字符串
    
    */
    public function  getHbXmlParams($mch_billno,$red_packet,$store_name, $customer_id){
        $params = [
            'nonce_str' => createNonceStr(),//随机字符串
            'mch_billno' =>$mch_billno,//商户订单号
            'mch_id' =>config('mch_id'),//商户号
            'wxappid' =>config('appid'),//公众账号appid
            'send_name' =>$store_name,//商户名称
            're_openid' => $customer_id,//用户openid
            'total_amount' =>100,//红包金额
            'total_num' =>1,//红包发放总人数
            'wishing' =>config('wishing'),//红包祝福语
            'client_ip' =>'47.93.11.60',// 调用接口的机器Ip地址
            'act_name' =>config('act_name'),//活动名称
            'remark' => config('remark'),//备注信息
            'scene_id'=>'PRODUCT_1' //场景ID PRODUCT_5:渠道分润
        ];
        $params['sign'] =getSign($params);//加入签名 
        return ArrToXml($params);
    }
    
    /**
     * 函数用途描述 :抽奖系统：折扣概率算法
     * @date: 2018年1月18日 上午10:14:19
     * @param:
     *  $store_id 门店ID
     * $customer_id 顾客ID
     * $money 订单金额
     * @return: 红包值
     */
    public function award_prob($store_id,$customer_id,$money,$mch_billno){
        

        $store_data =  StoreModel::where('id='.$store_id)->find();
        //获取商铺信息
        $shop_data =  ShopModel:: where('id='.$store_data['shop_id'])->find();
        //获取分公司信息
        $filiale_data = FilialeModel::where('id='.$shop_data['filiale_id'])->find();
        //获取中奖概率
        $award_data = AwardModel::where('filiale_id='.$filiale_data['id'])->find();
        if($award_data==null){
            $award_data = AwardModel::where('filiale_id=0')->find();
        }
        //获取具体折扣概率
        $discount_data = DiscountModel::where('shop_id is null and filiale_id='.$filiale_data['id'])->find();
        if($discount_data==null){
            $discount_data = DiscountModel::where('shop_id is null and filiale_id=0')->find();
        }
        //获取返还红包比例
        $account_data =  AccountModel::where('shop_id='.$shop_data['id'])->find();
        if($account_data==null){
            $account_data =  AccountModel::where('shop_id = 0 and filiale_id = '.$filiale_data['id'])->find();
        }
        $award_percent = $account_data['award_percent'];
        $purpose = 1;
        if($money>=10){
            
            //判断是否中奖
            if(rand(0,100) <= $award_data['prob']){
                //如果中奖了，执行中奖概率算法
                $sum = 100;
                $arr = array(array(0,$discount_data['prob1']),array(rand(1,20),$discount_data ['prob2']),array(rand(21,80),$discount_data['prob3']),array(rand(81,bcsub(100, $award_percent,2)),$discount_data['prob4']));
                for($i = 0;$i<count($arr);$i++){
                    if(rand(0,$sum)<=$arr[$i][1]){
                        //获取具体中奖红包金额
                        $award_money = bcdiv(bcmul($money,bcsub(100,$arr[$i][0],2)),100,2);
                        break;
                    }else{
                        $sum = bcsub($sum,$arr[$i][1],2);
                    }
                }
                if($filiale_data['hbmoney']<$award_money){
                    $purpose = 1;
                    $award_money = bcmul($money,bcdiv($award_percent,100,2),2);
                    if($award_money<0.3){
                        $award_money = 0.3;
                    }
                }else{
                    $purpose = 3;
                    $hbmoney['hbmoney'] = bcsub($filiale_data['hbmoney'], $award_money,2);
                    FilialeModel::startTrans();
                    if(FilialeModel::where('id='.$filiale_data['id'])->save($hbmoney)>0){
                        FilialeModel::commit();
                    }else{
                        FilialeModel::rollback();
                    }
                }
            }else{
                $shop_discount_data = DiscountModel::where('shop_id='.$shop_data['id'])->find();
                if($shop_discount_data==null){
                    $discount_data = DiscountModel::where('shop_id=0')->find();
                }
                $sum2 = 100;
                $award_money  = 0;
                $arr2 = array(array(0,$shop_discount_data['prob1']),array(rand(1,20),$shop_discount_data ['prob2']),array(rand(21,80),$shop_discount_data['prob3']),array(rand(81,bcsub(100, $award_percent,2)),$shop_discount_data['prob4']));
                for($i = 0;$i<count($arr2);$i++){
                    if(rand(0,$sum2)<=$arr2[$i][1]){
                        //获取具体中奖红包金额
                        $award_money = bcdiv(bcmul($money,bcsub(100,$arr[$i][0],2)),100,2);
                        break;
                    }else{
                        $sum = bcsub($sum,$arr[$i][1],2);
                    }
                }
                if($shop_data['shop_hb_money']<$award_money||$award_money==0){
                    $purpose = 1;
                    $award_money = bcmul($money,bcdiv($award_percent,100,2),2);
                    if($award_money<0.3){
                        $award_money = 0.3;
                    }
                }else{
                    $purpose = 4;
                    if($award_money<0.3){
                        $award_money = 0.3;
                    }
                    $hbmoney['shop_hb_money'] = bcsub($shop_data['shop_hb_money'], $award_money,2);
                    ShopModel::startTrans();
                    if(ShopModel::where('id='.$shop_data['id'])->save($hbmoney)>0){
                        ShopModel::commit();
                    }else{
                        ShopModel::rollback();
                    }
                }
            }
        }else{
            $award_money = 0;
        }
        if($money>$award_data['maxmoney']){
            $award_money = bcmul($money,bcdiv($award_percent,100,2),2);
            if($award_money<0.3){
                $award_money = 0.3;
            }
        }
        //         if($award_money>=0.3){
        //             $record_statu=1;
        //         }else{
        $record_statu=0;
        //           }
        //插入中奖纪录
        $record_data = ['mch_billno'=>$mch_billno,'customer_id'=>$customer_id,'shop_id'=>$shop_data['id'],'filiale_id'=>$filiale_data['id'],'store_id'=>$store_id,'order_money'=>$money,'award_money'=>$award_money,'create_time'=>date("Y-m-d H:i:s",time ()),'record_statu'=>$record_statu,'purpose'=>$purpose];
       AwardrecordModel::create($record_data);
        //返回返还红包金额
        return $award_money;
    }
}

